<template>
  <div id="box" class="box">
    
    <div class="content">
      <div class="content-left">
        <div class="content-left-name">
          <!-- <el-row>
            <el-col :span="6">
              <div>PG /</div>
            </el-col>
            <el-col :span="18">
              <div>优先 4</div>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="6">
              <div>项目号</div>
            </el-col>
            <el-col :span="18">
              <div>{{ currentRow.projectCode }}</div>
            </el-col>
          </el-row>
        </div>
        <div class="content-left-type">
          <div v-for="(item, index) in backgroudList" :key="index">
            <span class="block" :style="item.style" />
            <span>{{ item.label }}</span>
          </div>

        </div>
      </div>
      <div class="content-right"><el-button :loading="downloadLoding" @click="downloadImg">下载</el-button></div>
    </div>
    <!-- <div v-show="title" class="title">{{ title }} <span>|</span><span>{{ $t('lang.tableCorrelation') }}</span></div> -->
    <div id="simple-container" />
  </div>
</template>
<script>
import NodeItem from './components/node.vue'
import { Graph } from '@antv/x6'
import { Export } from '@antv/x6-plugin-export' // 导出图片
import { register } from '@antv/x6-vue-shape' // 引入vue渲染节点
import { GRAPH_CONFIG, CONNECTING_CONFIG } from './utils/index.js' // 节点信息及处理节点格式方法放在index.js内，在下一个步骤
import Hierarchy from '@antv/hierarchy' // 引入计算节点位置
// import { queryCodeValueByFiledName } from '@/api/topia/baseInfo/generalCode'
import moment from 'moment'
import TESTDATA  from './utils/data.js'
let graph

export default {
  name: 'TableCorrelationAntvIndex',
  props: {
    title: {
      type: String,
      default: ''
    },
    antvFlag: {
      type: Boolean,
      default: false
    },
    currentRow: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      backgroudList: [
        {
          type: 'yellow',
          label: '',
          style: {
            border: '1px solid #CAB003',
            background: '#FEF8CD'
          }
        },
        {
          type: 'blue',
          label: '',
          style: {
            border: '1px solid #0082E1',
            background: '#93D5F6'
          }
        },
        {
          type: 'green',
          label: '',
          style: {
            border: '1px solid #14A01E',
            background: '#D0ECD2'
          }
        },
        {
          type: 'blue1',
          label: '',
          style: {
            border: '1px solid #005495',
            background: '#CCDDEA'
          }
        },
        {
          type: 'purple',
          label: '',
          style: {
            border: '1px solid #9E168D',
            background: '#E4B9D8'
          }
        },
        {
          type: 'red',
          label: '',
          style: {
            border: '1px solid #FF0000',
            background: '#FFCCCC'
          }
        },
        {
          type: 'orange',
          label: '',
          style: {
            border: '1px solid #FF8349',
            background: '#FFDBB6'
          }
        }
        // {
        //   type: 'green1',
        //   label: '',
        //   style: {
        //     border: '1px solid #87C113',
        //     background: '#E4F89F'
        //   }
        // }
      ],
      sourceTypeList: [],
      // 默认样式
      defaultObj: {
        type: 'grey',
        label: '',
        style: {
          border: '1px solid #ccc',
          background: '#eee'
        }
      },
      downloadLoding: false
    }
  },
  
  mounted() {
    // 注册自定义组件
    register({
      shape: 'node-item-simple',
      component: {
        render: (h) => {
          return h(NodeItem, {
            on: {
              // 监听子组件触发的自定义事件
              myCustomEvent: (data) => {
                // 处理自定义事件
                this.handleCustomEvent(data)
              }
            }
          })
        }
      }
      // component: NodeItem // 节点组件
    })
    
    const initData = this.formatDataSimple(TESTDATA[0])
    this.graphInit(initData)
  },
  methods: {
    // 遍历循环数据--简易预览
    formatDataSimple(data) {
      const { child, partCode, id } = data
      return {
        // ...data,
        id,
        width: 450,
        height: 28,
        label: partCode,
        data, // 用来自定义节点展示节点信息，及节点连接桩信息
        children: child ? child.map(item => this.formatDataSimple(item)) : []
      }
    },
    handleCustomEvent(data) {
      data.collapse()
    },
    downloadImg() {
      this.downloadLoding = true
      graph.use(new Export())
      graph.toPNG((dataUri) => {
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = `${this.currentRow.projectCode}:${moment().format('YYYY-MM-DD HH:mm:ss')}`
        a.href = dataUri
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL 对象
        document.body.removeChild(a)
        this.downloadLoding = false
      }, {
        // 导出图片样式会乱需要手动配置样式
        stylesheet: `
          .item .header .el-row {
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
          }
          [class*=el-col-] {
            float: left;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
          }
          .item .content {
            border: 1px solid #D3D5D6;
            border-width: 1px 0;
          }
          .item .content .content-left {
              text-align: center;
              height: 115px;
              line-height: 115px;
          }
          .item .content .content-right {
              height: 115px;
              border-left: 1px solid #D3D5D6;
          }
          .text-center {
            text-align: center;
          }
          .flex-center {
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .bor-top {
            border-top: 1px solid #D3D5D6;
          }
          .bor-left {
            border-left: 1px solid #D3D5D6;
          }
          .item .header .el-col:first-child {
            border: none;
          }
          .el-col {
            border-right: 1px solid #D3D5D6;
            text-align: center;
          }
          .el-col-2 {
              width: 8.33333%;
          }
          .el-col-6 {
            width: 25%;
            
          }
          .el-col-8 {
            width: 33.33333%;
          }
          .el-col-12 {
            width: 50%;

          }
          .el-col-16 {
            width: 66.66667%;

          }
          .el-col-18 {
              width: 75%;
          }
          .el-col-24 {
            width: 100%;
          }
        `
      })
    },
    // 根据来源类型获取背景色
    getPartSourceType(type) {
      const obj = this.backgroudList.find(item => item.label === type)
      return obj || this.defaultObj
    },
   
    refreshData(data) {
      // 清空画布
      // graph.clearCells()
      // 格式化数据，计算节点位置
      const result = Hierarchy.mindmap(data, {
        direction: 'H',
        getHeight(d) {
          return d.height - 50
        },
        getWidth(d) {
          return d.width + 20
        },
        getHGap() {
          return 40
        },
        getVGap() {
          return 40
        },
        getSide: () => {
          return 'right'
        }
      })
      const cells = []
      const traverse = (hierarchyItem) => {
        if (hierarchyItem) {
          const { data, children } = hierarchyItem
          cells.push(
            graph.createNode({
              ...data,
              shape: 'node-item-simple',
              x: hierarchyItem.x,
              y: hierarchyItem.y,
              data: {
                ...data.data,
                expand: true, // 设置默认全部展开
                // sourceTypeStyle: this.getPartSourceType(data.data.partMaster.sourceType) // 根据零件来源类型获取背景色
              }
              // id: data.id,
              // width: data.width,
              // height: data.height,
              // label: data.label,
              // type: data.type

            })
          )

          cells.push(
            graph.createNode({
              ...data,
              shape: 'node-item-simple',
              x: hierarchyItem.x,
              y: hierarchyItem.y,
              data: {
                ...data.data,
                // sourceTypeStyle: this.getPartSourceType(data.data.partMaster.sourceType) // 根据零件来源类型获取背景色
              }
              // id: data.id,
              // width: data.width,
              // height: data.height,
              // label: data.label,
              // type: data.type

            })
          )

          if (children) {
            children.forEach((item) => {
              const { id, data } = item
              cells.push(
                graph.createEdge({
                  // shape: 'mindmap-edge', // 连接线的模板
                  source: {
                    cell: hierarchyItem.id,
                    anchor:
                      data.type === 'node-item-simple'
                        ? {
                          name: 'right',
                          args: {
                            dx: -6
                          }
                        }
                        : {
                          name: 'center',
                          args: {
                            dx: '25%'
                          }
                        }
                  },
                  target: {
                    cell: id,
                    anchor: {
                      name: 'left'
                    }
                  },
                  attrs: {
                    line: {
                      stroke: '#D3D5D6' // 连接线颜色
                      // targetMarker: null // 终止箭头
                    }
                  }
                })
              )
              traverse(item)
            })
          }
        }
      }
      traverse(result)

      // 重新绘制
      graph.resetCells(cells) // 清空画布并添加用指定的节点/边
      // graph.centerContent() // 居中显示
      graph.translate(360, 220) // 在 x、y 方向上平移画布
      // graph.zoomToFit({ padding: 10, maxScale: 1 }) // 缩放画布内容，使画布内容充满视口，并保证节点和边不变形
    },
    graphInit(nodeData) {
      graph = new Graph({
        container: document.getElementById('simple-container'),
        ...GRAPH_CONFIG,
        mousewheel: {
          enabled: true
          // modifiers: ['ctrl', 'meta'] // 设置缩放哪些键可以与交互一起使用，默认为 ['ctrl', 'meta']。
        },
        async: true, // 是否异步加载节点和边，默认为 false，如果为 true，则节点和边会以异步的方式加载。
        grid: true, // 网格，默认使用 10px 的网格，但不绘制网格背景。
        interacting: false, // 定制节点和边的交互行为,不否可拖拽
        connecting: { // 连线规则
          ...CONNECTING_CONFIG
        }
        // edge: {
        //   inherit: 'edge',
        //   connector: {
        //     name: 'mindmap'
        //   },
        //   attrs: {
        //     line: {
        //       targetMarker: '',
        //       stroke: '#A2B1C3',
        //       strokeWidth: 2
        //     }
        //   },
        //   zIndex: 0
        // }
      })

      // graph.size()
      this.refreshData(nodeData)
    },
    resetX6() {
      graph.removeCells()
    }
  }
}
</script>
<style scoped lang="scss">
.box {
  width: 100%;
  height: 100vh;

  .title {
    font-size: 16px;
    line-height: 24px;
    display: flex;

    &::before {
      content: '';
      width: 2px;
      height: 20px;
      background: #005495;
      display: inline-block;
      margin-right: 12px;
    }

    span {
      font-size: 12px;
      color: #666;
      margin-left: 12px;
    }
  }
}

#container {
  width: 100%;
  height: 100vh;
}

.content {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;

  .content-left {
    display: flex;

    .content-left-name {
      width: 250px;
      padding: 12px;
      @extend .bor;
      line-height: 22px;

      .el-col div:first-child {
        margin-bottom: 5px;
      }
    }

    .content-left-type {
      width: 510px;
      margin-left: 10px;
      padding: 12px;
      @extend .bor;
      display: flex;
      flex-wrap: wrap;

      div {
        width: 25%;
        line-height: 22px;
        font-size: 13px;
      }

      .block {
        width: 44px;
        height: 14px;
        display: inline-block;
        margin-right: 5px;
      }
    }
  }

  .content-right {}
}

.back-menu {
  font-size: 16px;
  color: #1E2329;
  padding: 0 12px;
  height: 36px;
  line-height: 36px;
  border-bottom: 1px solid #D3D5D6;
  margin-bottom: 12px;

  i {
    margin-right: 12px;
  }
}

.bor {
  border: 1px solid #D3D5D6;
  border-radius: 4px;
  height: 72px;
}

.pointer {
  cursor: pointer;
}
</style>
